﻿/**
*编制一张图（控制性详细规划）类
*@module modules.business
*@class DCI.Business.RegulatoryPlan
*@constructor initialize
*/
define("business/regulatoryplan", [
    "leaflet",
    "core/dcins",
    "plugins/scrollbar",
    "plugins/pagination"
], function (L) {

    L.DCI.Business.RegulatoryPlan = L.Class.extend({

        /**
        *类id
        *@property id
        *@type {String}
        *@private
        */
        id: 'business-compilemap-regulatoryplan',

        /**
        *保存当前的分页数据
        *@property data
        *@type {Object}
        *@private
        */
        data: null,

        /**
        *模块名称
        *@property _name
        *@type {String}
        *@private
        */
        _clsName: null,
        /**
        *保存过滤条件数据
        *@property queryData
        *@type {Object}
        *@private
        */
        queryData: null,

        /**
        *保存查看的详情的项目当前页索引号
        *@property detailDataIndex
        *@type {String}
        *@private
        */
        detailDataIndex: '0',


        /**
        *查询编制状态   (0为查询全部状态)
        *@property status
        *@type {String}
        *@private
        */
        status: '0',

        /**
        *筛选条件   (0为查询全部)
        *@property condition
        *@type {String}
        *@private
        */
        condition: '0',

        /**
        *总共有多少页数据
        *@property pageNum
        *@type {Number}
        *@private
        */
        pageNum: 0,

        /**
        *当前显示页码
        *@property currentPage
        *@type {Number}
        *@private
        */
        currentPage: 1,

        /**
        *每页最多显示内容个数
        *@property maxShowContentNum
        *@type {Number}
        *@private
        */
        maxShowContentNum: 10,


        /**
        *html模板
        *@property temp
        *@type {String}
        *@private
        */
        temp: '<div class="regulatoryplan active">'
                + '<div class="top"></div>'
                + '<div class="searchBar"><input type="text"/><span>搜索</span></div>'
                + '<div class="content"></div>'
                + '<div class="bottom"></div>'
             + '</div>'
             + '<div class="regulatoryplan-detail">'
                + '<div class="regulatoryplan-detail-title">'
                    + '<span class="turnback icon-return"></span>'
                    + '<div class="titlecontent"></div>'
                + '</div>'
                + '<div class="regulatoryplan-detail-content"></div>'
             + '</div>',

        /**
        *html详情模板
        *@property detailTemp
        *@type {String}
        *@private
        */
        detailTemp: '<div id="" class="regulatoryplan-detail-content-temple">'
                        + '<div>'
                            + '<span class="title"></span>'
                            + '<span class="operate" data-info="">查看附件</span>'
                        + '</div>'
                        + '<table class="table table-bordered">'
                            + '<tbody class="regulatoryplan-detail-content-tbody"></tbody>'
                        + '</table>'
                  + '</div>',

        /**
        *初始化
        *@method initialize
        */
        initialize: function () {
            this._clsName = Project_ParamConfig.bzOneMapConfig.name;
        },

        /**
        *获取内容模版
        *@method getBody
        *@return {String} 内容模版
        */
        getBody: function () {
            return this.temp;
        },

        /**
        *加载入口--控制性详细规划内容
        *@method load
        */
        load: function (isAddData) {
            $('.regulatoryplan .content').mCustomScrollbar({ theme: 'minimal-dark' });          //滚动条
            $('.regulatoryplan-detail-content').mCustomScrollbar({ theme: 'minimal-dark' });    //滚动条

            //插入过滤条件信息
            this.getQueryData();
            this.currentPage = 1;
            if (isAddData == undefined || isAddData == true)
                this.getPageData(this.currentPage, this.maxShowContentNum, this.status, this.condition);//获取控制性详细规划数据

            //点击状态
            $(".regulatoryplan .top").on('click', 'span:not(:last)', { context: this }, function (e) { e.data.context._switchTab(e); });
            //显示或隐藏搜索栏
            $(".regulatoryplan .top").on('click', 'span:last', { context: this }, function (e) { e.data.context._showSearch(e); });
            //点击搜索
            $(".regulatoryplan .searchBar").on('click', 'span', { context: this }, function (e) { e.data.context._clickSearch(e); });
            //搜索(回车键触发)
            $(".regulatoryplan .searchBar").on('keydown', 'input', { context: this }, function (e) {
                var e = e || window.event;
                if (e.keyCode == 13) {
                    e.data.context._clickSearch(e);
                    return false;
                }
            });

            //绑定查看项目触发事件
            $(".regulatoryplan").on('click', 'span.viewDetail', { context: this }, function (e) {
                e.data.context.viewDetail(e);
            });

            $(".regulatoryplan").on('click', 'div.percontent', { context: this }, function (e) {
                $(".regulatoryplan .percontent").removeClass("selected");
                $(e.currentTarget).addClass("selected");
                var id = $(e.currentTarget).children(".operation").children("span:last-child").attr("data-ajbm");
                e.data.context._zoomTo(id);
            });

            //返回按钮
            $(".regulatoryplan-detail").on('click', '.turnback', { context: this }, function (e) { e.data.context.turnBack(e); });
        },

        /**
        *获取过滤条件
        *@method getQueryData
        */
        getQueryData: function () {
            L.dci.app.services.businessService.getCompileMapConditionData({
                context: this,
                success: function (res) {
                    this.queryData = res;
                    this.insertAllStatus();         //插入状态信息
                },
                error: function () {
                    L.dci.app.util.dialog.alert("提示", "未找到对应的服务地址");
                }
            });
        },

        /**
        *获取分页数据（控制性详细规划）
        *@method getPageData
        *@param currentPage {Number}       当前请求的页码
        *@param maxShowNum {Number}        每页最多显示内容个数
        *@param status {String}            查询阶段
        *@param condition {String}         筛选条件
        */
        getPageData: function (currentPage, maxShowNum, status, condition) {
            var year = Project_ParamConfig.bzOneMapConfig.year;//时间
            L.dci.app.services.businessService.getCompileMapPageData({
                year: year,
                page: currentPage,
                maxShowNum: maxShowNum,
                status: status,
                condition: condition,
                context: this,
                success: function (res) {
                    this.data = null;
                    this.pageNum = 0;
                    this.data = res;
                    this.pageNum = this.data.PageCount;         //一共多少页
                    this.insertContent();                       //加载批后跟踪内容
                },
                error: function () {
                    L.dci.app.util.dialog.alert("提示", "未找到对应的服务地址");
                }
            });
        },

        /**
        *根据ID查询项目
        *@method queryByIds
        *@param items{Array} 结果数组
        */
        queryByIds: function (items) {
            $(".compilemap_tab>span:last-child").addClass("active").siblings().removeClass("active");
            $(".compilemap_tabContent2").addClass("active").siblings().removeClass("active");
            $(".regulatoryplan").addClass("active").siblings().removeClass("active");
            $(".regulatoryplan .top>span").removeClass("active");
            $(".regulatoryplan .top>span:first-child").addClass("active");

            var ids = [];
            for (var i = 0; i < items.length; i++) {
                ids.push(items[i].attributes[Project_ParamConfig.bzOneMapConfig.queryAttribute]);
            }
            if (ids.length == 0) {
                $(".regulatoryplan").addClass("active").siblings().removeClass("active");
                this.data = [];
                this._currentSelectedObj = null;
                this.insertContent();
                return;
            }
            this._currentSelectedObj = items[0];
            L.dci.app.services.businessService.queryBzByIds({
                caseIds: ids.join(','),
                context: this,
                success: function (res) {
                    this.data = null;
                    this.pageNum = 0;
                    this.data = res;
                    this.pageNum = this.data.PageCount;
                    if (res.Count == 1) {
                        $(".regulatoryplan-detail").addClass("active").siblings().removeClass("active");
                        this.insertContent();

                        this.currentAjbm = '';
                        $(".regulatoryplan-detail").siblings().removeClass("active").end().addClass("active");
                        var container = $(".regulatoryplan-detail-content .mCSB_container");
                        container.html("");
                        var obj = res.Objects[0];
                        var title = obj.PlanName;
                        $(".regulatoryplan-detail .titlecontent").html(title);

                        var fieldName = 'Ajbm';
                        if (obj["Xmbm"] != null && obj["Xmbm"] != "") {
                            fieldName = 'Xmbm';
                        }
                        var projectId = obj[fieldName];
                        var currentAjbm = obj.Ajbm;

                        $(".regulatoryplan-detail .projectBtn").attr("data-info", projectId);
                        this.getDetailData(fieldName, projectId, currentAjbm); //获取详情信息( 查询字段名、项目编码、案件编码)
                    } else {
                        this.insertContent();
                    }
                    //高亮列表栏项
                    var selecteds = $(".regulatoryplan .percontent");
                    var projectId;
                    for (var i = 0; i < selecteds.length; i++) {
                        projectId = $.trim($(selecteds[i]).children(".operation").children(".viewDetail").attr("data-projectid"));
                        if (projectId == ids[0]) {
                            $(selecteds[i]).addClass("selected");
                            break;
                        }
                    }
                }
            });
        },
        /**
        *插入全部状态内容
        *@method insertAllStatus
        */
        insertAllStatus: function () {
            var containerObj = $(".regulatoryplan>.top");
            var data = this.queryData[0].Values;       //获取所有编制状态
            var trHtml = '';

            for (var att in data) {
                if (data[att] == "全部")
                    trHtml += '<span class="active">全部</span>';
                else
                    trHtml += '<span>' + data[att] + '</span>';
            }
            trHtml += '<span class="search icon-search-icon"></span>';
            containerObj.html(trHtml);
        },

        /**
        *插入控制性详细规划内容
        *@method insertContent
        */
        insertContent: function () {
            //清空内容区域和页码区域
            var containerObj = $(".regulatoryplan .content .mCSB_container");
            containerObj.html("");
            $('.regulatoryplan .bottom').html("");
            var data = this.data.Objects;       //保存具体内容数据
            var columnName = this.data.Columns; //保存列名称
            //判断是否有匹配数据
            if (data == null || data.length == 0) {
                var html = '<p class="emptyResult">没有匹配的数据</p>';
                containerObj.html(html);
            }
            else {
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var trHtml = '';
                    var obj = data[i];
                    var fieldName = 'Ajbm';
                    var currentAjbm = data[i]["Ajbm"];     //默认查询详情用案件编码字段，当项目处于修编状态时，使用项目编码作为查询字段
                    var projectId = data[i]["Xmbm"];        //这里通过key获取对应的值，作为详情按钮的属性保存
                    var projectName = data[i]["PlanName"];  //这里通过key获取对应的值，作为详情按钮的属性保存
                    for (var att in obj) {//遍历要插入的字段信息
                        var key = att;
                        for (var kk in columnName) {//将英文字段名改为对应的中文名
                            if (att == kk) {
                                key = columnName[kk];
                                break;
                            }
                        }
                        //过滤不显示的字段
                        if (!L.dci.app.util.tool.isShowAttribute(Project_ParamConfig.bzOneMapConfig.attributes,att)) {
                            continue;
                        }
                        else if (att.indexOf("Time") > -1) {//开始时间处理   2014-09-10T00:00:00  去掉后面的时间，只保留日期
                            var str = obj[att];
                            var value = str.substring(0, str.indexOf(' '));
                            trHtml += '<tr><td>' + key + ':</td><td>' + value + '</td></tr>';
                        }
                        else {
                            if (obj[att] == null)
                                trHtml += '<tr><td>' + key + ':</td><td></td></tr>';
                            else
                                trHtml += '<tr><td>' + key + ':</td><td>' + obj[att] + '</td></tr>';
                        }
                    }
                    var number = i + 1;
                    if (parseInt(data[i]["IsPlan"]) > 1) {
                        fieldName = 'Xmbm';
                        html += '<div class="percontent">'
                            + '<div class="pic1">'
                            + '</div>'
                            + '<div class="percontent-content">'
                            + '<table>'
                            + '<tbody>'
                            + trHtml
                            + '</tbody>'
                            + '</table>'
                            + '</div>'
                            + '<div class="operation">'
                            + '<span class="iconMark"></span>' //当项目处于修编状态时，添加类.iconMark显示修编图标
                            + '<span class="viewDetail" number = ' + number + ' data-fieldName="' + fieldName + '" data-ajbm="' + currentAjbm + '"  data-projectid="' + projectId + '" data-projectname="' + projectName + '">详情</span>'
                            + '</div>'
                            + '</div>';
                    } else {
                        html += '<div class="percontent">'
                            + '<div class="pic1">'
                            + '</div>'
                            + '<div class="percontent-content">'
                            + '<table>'
                            + '<tbody>'
                            + trHtml
                            + '</tbody>'
                            + '</table>'
                            + '</div>'
                            + '<div class="operation">'
                            + '<span class=""></span>' //当项目不处于修编状态时，去掉类.iconMark不显示修编图标
                            + '<span class="viewDetail" number = ' + number + ' data-fieldName="' + fieldName + '" data-ajbm="' + currentAjbm + '" data-projectid="' + projectId + '" data-projectname="' + projectName + '">详情</span>'
                            + '</div>'
                            + '</div>';
                    }
                }
                containerObj.html(html);

                //调用分页函数
                var _this = this;
                var page = new L.DCI.Pagination({
                    pageCount: this.pageNum,
                    currentPage: this.currentPage,
                    showPageNum: 5,
                    containerObj: $('.regulatoryplan .bottom'),
                    pageChange: function (page) {
                        _this.changePage(page);
                    }
                });
            }
        },

        /**
        *切换编制状态
        *@method _switchTab
        */
        _switchTab: function (e) {
            var map = L.DCI.App.pool.get('MultiMap').getActiveMap();
            map.getHighLightLayer().clearLayers();
            var eleActive = 'active';
            var targetObj = $(e.target);
            targetObj.siblings().removeClass(eleActive);
            targetObj.addClass(eleActive);
            var text = targetObj.text();
            //隐藏搜索栏
            this._hideSearch();
            if (text == "全部") {
                this.status = "0";
            } else {
                var obj = this.queryData[0].Values;
                for (var att in obj) {
                    if (obj[att] == text) {
                        this.status = att;
                        break;
                    }
                }
            }
            //恢复当前页为第一页
            this.currentPage = 1;
            this.getPageData(this.currentPage, this.maxShowContentNum, this.status, 0);
        },

        /**
        *显示搜索栏
        *@method _showSearch
        */
        _showSearch: function (e) {
            if (!$(".regulatoryplan .searchBar").hasClass("active")) {
                $(".regulatoryplan .searchBar").addClass("active");
                $(".regulatoryplan .mCSB_container").addClass("searchBarActive");
            }
            else {
                this._hideSearch();
            }
        },

        /**
        *隐藏搜索栏
        *@method _hideSearch
        */
        _hideSearch: function (e) {
            $(".regulatoryplan>.searchBar>input").val("");
            $(".regulatoryplan .searchBar").removeClass("active");
            $(".regulatoryplan .mCSB_container").removeClass("searchBarActive");
            this.condition = 0;
        },

        /**
        *点击搜索
        *@method _clickSearch
        */
        _clickSearch: function (e) {
            var condition = $.trim($(".regulatoryplan>.searchBar>input").val());
            if (condition == "") {
                this.condition = "0";
            } else {
                this.condition = condition;
            }
            //恢复当前页为第一页
            this.currentPage = 1;
            this.getPageData(this.currentPage, this.maxShowContentNum, this.status, this.condition);
        },

        /**
        *详情点击事件
        *@method viewDetail
        */
        viewDetail: function (e) {
            this.currentAjbm = '';
            $(".regulatoryplan-detail").siblings().removeClass("active").end().addClass("active");
            var container = $(".regulatoryplan-detail-content .mCSB_container");
            container.html("");
            var title = $(e.target).attr("data-projectname");
            $(".regulatoryplan-detail .titlecontent").html(title);
            var fieldName = $(e.target).attr("data-fieldName");
            var projectId = $(e.target).attr("data-projectid");
            var currentAjbm = $(e.target).attr("data-ajbm");
            this.detailDataIndex = $(e.target).attr("number");  //保存当前的项目索引

            $(".regulatoryplan-detail .projectBtn").attr("data-info", projectId);
            this.getDetailData(fieldName, projectId, currentAjbm); //获取详情信息( 查询字段名、项目编码、案件编码)
        },

        /**
        *改变页码
        *@method changePage
        *@param page {Object}       当前请求的页码
        */
        changePage: function (page) {
            this.currentPage = page;
            this.getPageData(page, this.maxShowContentNum, this.status, this.condition);
        },

        /**
        *返回
        *@method turnBack
        */
        turnBack: function () {
            $(".regulatoryplan-detail").removeClass("active").siblings().addClass("active");
            //恢复默认值
            this.detailDataIndex = '0';
        },

        /**
        *获取详情数据
        *@method getDetailData
        *@param fieldName {String}       查询字段名称
        *@param projectId {String}       项目编码Xmbm
        *@param currentAjbm {String}     案件编码Ajbm
        */
        getDetailData: function (fieldName, projectId, currentAjbm) {
            L.dci.app.services.businessService.getCompileMapDetailData({
                fieldName: fieldName,
                projectId: projectId,
                currentAjbm: currentAjbm,
                context: this,
                success: function (res) {
                    var data = res;
                    //插入信息
                    for (var i = 0; i < data.length; i++) {
                        var ajbm = data[i].Values.案件编码;
                        var currentAjbm = this.currentAjbm;         //当前点击的项目的案件编码
                        var container = $(".regulatoryplan-detail-content .mCSB_container");
                        container.append(this.detailTemp);
                        $(".regulatoryplan-detail a#targetDivId").attr("href", "#" + currentAjbm);
                        $(".regulatoryplan-detail-content-temple:last").attr("id", ajbm);        //给每个容器添加对应的ajbm
                        var titleObj = $(".regulatoryplan-detail .regulatoryplan-detail-content-temple:last-child .title");
                        var tbodyObj = $(".regulatoryplan-detail .regulatoryplan-detail-content-temple:last-child .regulatoryplan-detail-content-tbody");
                        titleObj.html(data[i].Key);//插入标题
                        var trHtml = '';
                        for (var att in data[i].Values) {
                            if (att == "要素ID" || att == "CAD图层名" || att == "实体标识") {
                                continue;
                            }
                            if (att.indexOf("时间") > -1) {//时间处理   2014-09-10T00:00:00  去掉后面的时间，只保留日期
                                var value = data[i].Values[att].substring(0, data[i].Values[att].indexOf(' '));
                                trHtml += '<tr><td class="tdTitle">' + att + '</td><td>' + value + '</td></tr>';
                            } else
                                trHtml += '<tr><td class="tdTitle">' + att + '</td><td>' + data[i].Values[att] + '</td></tr>';
                        }
                        tbodyObj.html(trHtml);
                    }
                },
                error: function () {
                    L.dci.app.util.dialog.alert("提示", "未找到对应的服务地址");
                }
            });
        },       
        /**
        *根据当前ID定位项目
        *@method _zoomTo
        *@param value{Array}ID数组
        */
        _zoomTo: function (value) {
            var _map = L.DCI.App.pool.get('MultiMap').getActiveMap().getMap();
            _map.eachLayer(function (layer) {
                if (layer.options
                    && layer.options.id != "baseLayer"
                    && layer.options.id != null
                    && layer.options.name == this._clsName) {
                    layer.metadata(function (error, metadata) {
                        if (metadata == null) return;
                        var layers = [];
                        for (var i = 0 ; i < metadata.layers.length; i++) {
                            layers.push(metadata.layers[i].id.toString());
                        }
                        L.dci.app.util.locate.doFind(layer.url, layers, Project_ParamConfig.bzOneMapConfig.zoomItemName, value);
                    }, this);
                }
            }, this);
        },
        /**
        *高亮当前高亮对象
        *@method showMarks
        */
        showMarks: function () {
            if (this._currentSelectedObj != null) {
                var _map = L.DCI.App.pool.get('MultiMap').getActiveMap();
                L.dci.app.util.highLight(_map, this._currentSelectedObj, true, false, this._currentSelectedObj.geometry.type);
            }
        }

    });
    return L.DCI.Business.RegulatoryPlan;
});